<template>
  <el-main>
    <el-row class="search">
      <el-col :span="24">
        <el-form :inline="true" :model="searchForm" class="demo-form-inline">
          <el-form-item label="区域搜索：">
            <el-input
              v-model="searchForm.name"
              placeholder="请输入"
              size="medium"
              style="width: 203px"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              @click="onSubmit"
              icon="el-icon-search"
              size="medium"
              style="width: 80px"
              >查询</el-button
            >
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <AreaOrder
      :visible.sync="addVisible"
      ref="addNode"
      :totalList="tableData"
      :regionForm="regionForm"
      :rules="regionRules"
      @beforeClose="beforeClose"
      @submit="submit"
      :type="type"
    >
      <template v-if="type !== 'preview'" v-slot="{ rules }">
        <el-form :model="regionForm" ref="regionForm" :rules="rules">
          <el-form-item
            label="区域名称："
            :label-width="'140px'"
            prop="regionName"
          >
            <el-input
              v-model="regionForm.regionName"
              autocomplete="off"
              placeholder="请输入"
              maxlength="15"
              show-word-limit
            ></el-input>
          </el-form-item>
          <el-form-item label="备注说明：" :label-width="'140px'" prop="remark">
            <el-input
              type="textarea"
              :rows="3"
              placeholder="请输入备注（不超过40字）"
              v-model="regionForm.remark"
              maxlength="40"
              show-word-limit
            >
            </el-input>
          </el-form-item>
        </el-form>
      </template>

      <template v-if="type === 'preview'">
        <el-form>
          <el-form-item label="区域名称：" :label-width="'140px'">
            <span>{{ areaName }}</span>
          </el-form-item>
          <el-form-item label="包含点位：" :label-width="'140px'" prop="remark">
            <el-table
              v-loading="loading"
              :data="previewList"
              empty-text
              :cell-style="{ padding: '2px 0', border: 'none' }"
              :header-cell-style="{ background: '#f4f6fa' }"
            >
              <el-table-column label="序号" type="index" :index="1" width="80">
              </el-table-column>
              <el-table-column label="点位名称" width="158">
                <template slot-scope="area">
                  <span>{{ area.row.name }}</span>
                </template>
              </el-table-column>
              <el-table-column label="设备数量" width="158">
                <template slot-scope="area">
                  <span>{{ area.row.vmCount }}</span>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-form>
      </template>
    </AreaOrder>
    <el-row class="list">
      <el-col :span="24">
        <el-row class="add"
          ><el-col
            ><el-button
              icon="el-icon-circle-plus-outline"
              @click="(type = 'add') && (addVisible = true)"
              >新建</el-button
            ></el-col
          ></el-row
        >
        <el-row class="table">
          <el-col>
            <ListTable
              :tableData="tableData"
              :loading="loading"
              @handlePreview="handlePreview"
              @handleEdit="handleEdit"
              @handleDelete="handleDelete"
            ></ListTable>
          </el-col>
        </el-row>
        <el-row class="page">
          <el-col :span="20">
            <span
              >共{{ totalCount }}条记录&nbsp;&nbsp;第&nbsp;{{ pageIndex }}/{{
                totalPage
              }}&nbsp;页</span
            >
          </el-col>
          <el-col :span="2">
            <el-button
              @click="handlePage('dec')"
              :disabled="pageIndex === '1'"
              :class="{ disable: pageIndex === '1' }"
              >上一页</el-button
            >
          </el-col>
          <el-col :span="2">
            <el-button
              @click="handlePage('add')"
              :disabled="pageIndex === totalPage"
              :class="{ disable: pageIndex === totalPage }"
              >下一页</el-button
            >
          </el-col>
        </el-row>
      </el-col>
    </el-row>
  </el-main>
</template>
<script>
import AreaOrder from './components/BuildTable.vue'
import ListTable from './components/ListTable.vue'
import {
  delRegion,
  regionSearch,
  addRegion,
  editNode,
  searchNode
} from '@/api/dianwei'
export default {
  components: {
    AreaOrder,
    ListTable
  },
  data () {
    return {
      searchForm: {
        name: ''
      },
      type: '',
      tableData: [],
      pageIndex: 1,
      pageSize: 10,
      totalCount: 0,
      totalPage: 0,
      addVisible: false,
      loading: false,
      currentRow: {},
      regionForm: {
        regionName: '',
        remark: ''
      },
      regionRules: {
        regionName: [
          { required: true, message: '请输入区域名称', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              let isRepeat = false
              // 如果有id就是编辑 名称是否重复的条件需要排除自己 否则就是新增 完全不可以重复
              if (this.regionForm.id) {
                isRepeat = this.tableData
                  .filter((item) => item.id !== this.regionForm.id)
                  .some((item) => item.name === value)
                console.log(isRepeat)
              } else {
                // 如果有重复的就校验失败
                isRepeat = this.tableData.some((item) => item.name === value)
              }
              // eslint-disable-next-line new-cap
              isRepeat
                ? callback(
                  new Promise(this.$message.error('已存在此名称的区域'))
                )
                : callback()
            },
            trigger: 'submit'
          }
        ],
        remark: {
          required: true,
          message: '备注不可以为空喔～',
          trigger: 'blur'
        }
      },
      areaName: '',
      previewList: []
    }
  },
  async created () {
    this.getList()
  },
  methods: {
    onSubmit () {
      this.getList(this.searchForm.name)
    },
    async handlePreview (index, row) {
      this.type = 'preview'
      // console.log(row)
      this.areaName = row.name
      const res = await searchNode({
        pageIndex: this.pageIndex,
        pageSize: this.pageSize,
        regionId: row.id
      })
      this.previewList = res.currentPageRecords
      this.addVisible = true
    },
    handleEdit (index, row) {
      // this.currentRow = row
      this.type = 'edit'
      // 修改弹窗中的内容
      this.regionForm = { ...row, regionName: row.name, nodeCount: '' }
      this.addVisible = true
    },
    async handleDelete (index, row) {
      // console.log(index, row)
      try {
        // 有点位数就可以删除成功
        await delRegion(row.id)
        this.$message.success('删除成功')
        this.getList()
      } catch (e) {
        console.log(e)
        this.$notify.info({
          title: '提示',
          message: e.response.data,
          iconClass: 'message-icon'
        })
      }
    },
    async getList (name) {
      try {
        this.loading = true
        let res = []
        // 如果是搜索就要传name参数
        if (name) {
          res = await regionSearch({
            pageIndex: this.pageIndex,
            pageSize: this.pageSize,
            name
          })
        } else {
          res = await regionSearch({
            pageIndex: this.pageIndex,
            pageSize: this.pageSize
          })
        }
        this.tableData = res.currentPageRecords
        this.pageIndex = res.pageIndex
        this.totalCount = res.totalCount
        this.totalPage = res.totalPage
      } finally {
        this.loading = false
      }
    },
    handlePage (type) {
      if (type === 'dec') {
        if (this.pageIndex > 1) this.pageIndex--
      }
      if (type === 'add') {
        if (this.pageIndex < this.totalPage) this.pageIndex++
      }
      this.getList()
    },
    beforeClose () {
      // 如果有id就手动恢复 防止新增时数据没有改变回去
      this.regionForm = {
        regionName: '',
        remark: ''
      }
      this.addVisible = false
      // console.log(this.$refs.regionForm)
      // 如果不是预览的表单则需要重置
      if (this.type !== 'preview') {
        this.$refs.regionForm.resetFields()
      }
    },
    async submit () {
      // 提交后验证 发请求 触发父级更新列表
      try {
        await this.$refs.regionForm.validate()
        // 如果有id就发送编辑请求
        if (this.regionForm.id) {
          await editNode(this.regionForm)
          this.$message.success('修改成功！')
        } else {
          await addRegion(this.regionForm)
          this.$message.success('新增成功！')
        }
        this.beforeClose()
        this.getList()
      } catch (e) {}
    }
  }
}
</script>

<style lang="scss" scoped>
* {
  box-sizing: border-box;
}
.el-main {
  width: 89vw;
  background-color: #f8fafd;
  color: #333;
  display: block;
}
.el-row {
  margin-bottom: 20px;
  border-radius: 0;
  &.search {
    height: 64px;
    background-color: white;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  &.list {
    margin-bottom: 0;
    background-color: white;
    // height: 673px;
  }
}

.el-form--inline {
  height: 100%;
  .el-form-item {
    height: 100%;
    margin-bottom: 0;
    // padding-top: 12px;
    ::v-deep .el-form-item__label {
      color: #606266;
      padding-left: 17px;
    }
    .el-button--medium {
      padding: 0;
      height: 36px;
      background-color: #6783f7;
      color: white;
      border: none;
      line-height: 36px;
    }
  }
}

::v-deep i {
  font-size: 16px;
  vertical-align: middle;
}
::v-deep span {
  // margin-left: 8px !important;
  vertical-align: middle;
}
.add {
  // height: 36px;
  margin: 20px 0;
  .el-button {
    padding: 0;
    // height: 100%;
    width: 80px;
    background: linear-gradient(135deg, #ff9743, #ff5e20) !important;
    border: none;
    line-height: 36px;
    color: white;
    margin-left: 17px;
  }
}

.table {
  // height: 482px;
  max-width: 100%;
  background-color: white;
  padding: 0px 15px 0px 17px;
  margin-bottom: 0;
}

.page {
  // background-color: #d6ddf6;
  // height: 96px;
  padding: 32px 16px 32px 33px;
  .el-button {
    height: 32px;
    width: 70px;
    padding: 0;
    margin: 0 16px;
    border: none;
    background-color: #d6ddf6;
    color: black;
    font-weight: 200;
    font-size: 13px;
    border-radius: 2px;
    &.disable {
      background-color: #eef0f8;
      color: #d9dde2;
    }
  }
  span {
    font-size: 16px;
    color: #dbdfe5 !important;
    margin-right: 10px;
    font-weight: 400;
  }
}
</style>
<style lang="scss">
.message-icon {
  color: #f58646 !important;
}
</style>
